package com.cb.controller.front.order;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONML;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.tempuri.ServiceSoap;

import webservices.alipaydirect.util.UtilDate;
import webservices.sbe.InsuranceSbeManager;

import com.cb.common.util.ConfigUtil;
import com.cb.common.webService.ClientService;
import com.cb.core.command.QueryFilter;
import com.cb.core.controller.BaseListController;
import com.cb.core.util.DateUtil;
import com.cb.domain.model.order.BOrder;
import com.cb.domain.model.order.Flight;
import com.cb.domain.model.order.InsuranceCompany;
import com.cb.domain.model.order.PassengerDto;
import com.cb.domain.model.order.Policy;
import com.cb.domain.model.system.City;
import com.cb.domain.model.system.SystemHelp;
import com.cb.domain.service.Insurance.FactoryInsuranceCreater;
import com.cb.domain.service.order.BOrderManager;
import com.cb.domain.service.order.InsuranceCompanyManager;
import com.cb.domain.service.order.OrderLogManager;
import com.cb.domain.service.order.PolicyManager;
import com.cb.domain.service.system.CityManager;
import com.cb.domain.service.system.SystemHelpManager;

/**
 * 
 * @Author author
 * @Vesion 1.0 Create Time:
 *         <p>
 *         <b>Class Description:</b>[TODO]
 *         <p>
 */

public class OrderSearchController extends BaseListController {

	@Autowired
	private CityManager cityManager;

	@Autowired
	private BOrderManager bOrderManager;

	@Autowired
	protected PolicyManager policyManager;

	@Autowired
	private SystemHelpManager systemHelpManager;
	@Autowired
	private OrderLogManager orderLogManager;
	@Autowired
	private InsuranceSbeManager insuranceSbeManager;
	
	@Autowired
	protected InsuranceCompanyManager insuranceCompanyManager;
	@Autowired
	private FactoryInsuranceCreater factoryInsuranceCreater;

	@Override
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		List<SystemHelp> systemHelps = systemHelpManager.getAll();

		request.setAttribute("systemHelps", systemHelps);

		return new ModelAndView("/front/order/search");
	}

	// 支付页面
	public ModelAndView affirmance(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		BOrder bOrder=null;
		try{
		bOrder = Order(request);
		}catch (Exception e) {
			return new ModelAndView("/front/order/orderCreateError");
		}
		ClientService<ServiceSoap> clientService = new ClientService<ServiceSoap>();
		ServiceSoap service = clientService.getClient("abeService.path",
				ServiceSoap.class);


		String identity = getIdentity();/*
										 * String requests =
										 * "<?xml version='1.0'?>" +
										 * "<ABE_PATByFlights_1_2>" +
										 * "<PatPara>PAT:A</PatPara>" +
										 * "<FlightSegments><FlightSegment>" +
										 * "<Carrier>MU</Carrier>" +
										 * "<FlightNo>5216</FlightNo>" +
										 * "<BoardPoint>CAN</BoardPoint>" +
										 * "<OffPoint>PEK</OffPoint>" +
										 * "<DepatureDate>2012-3-30</DepatureDate>"
										 * + "<ClassCode>Y</ClassCode>" +
										 * "<ActionCode>NN</ActionCode>" +
										 * "</FlightSegment></FlightSegments>" +
										 * "<PNR></PNR><" +
										 * "PriceType></PriceType>" +
										 * "<Farebasis></Farebasis>" +
										 * "<AllowActionCode></AllowActionCode>"
										 * + "</ABE_PATByFlights_1_2>";
										 * 
										 * String filter = "";
										 */

		// ABE_AVDataset_1_3 查询单条航班信息
		// String result = service.abeSubmit(identity, requests, filter);
		
		String departure_city=request.getParameter("departure_city");

		String arrival_city=request.getParameter("arrival_city");
		
		City depCity=cityManager.getCity(departure_city);
		City arriCity=cityManager.getCity(arrival_city);
		
		String departure_day=request.getParameter("departure_day");
		String flight_no=request.getParameter("flight_no");
		String sendMsg=getText("flight.message", new Object[]{departure_day,depCity.getCtCn(),arriCity.getCtCn(),flight_no,bOrder.getOrderNo()});
		bOrderManager.saveOrderAndLog(bOrder,sendMsg);
		Map<String, Object> model=new HashMap<String, Object>();
		model.put("message", sendMsg);
		if(StringUtils.isNotBlank(bOrder.getContactEmail())){
		mailEngine.sendTemplateMail("registerTicket.vm", model, "订单预定成功", null, 
				new String[]{bOrder.getContactEmail()}, null, null, null, null, true);
		}
		return new ModelAndView(
				"redirect:/front/order/orderSearch.do?cmd=doAffirmance&orderId="
						+ bOrder.getId());
	}

	private BOrder Order(HttpServletRequest request) throws Exception{
		String identity=getIdentity();
		return AbeUtil.convertOrder(request,policyManager,insuranceCompanyManager,identity);
	}

	// 查询航班
	public void searchOrder(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
	
		ClientService<ServiceSoap> clientService = new ClientService<ServiceSoap>();

		ServiceSoap service = clientService.getClient("abeService.path",ServiceSoap.class);

		String flightCode =request.getParameter("flightCode");
		String arriCode = request.getParameter("arriCode");
		
		 String flightDate=request.getParameter("flightDate");
		 

		String identity = getIdentity();
	
		String requests = getText("abe.request", new Object[] { flightCode, arriCode,
				flightDate });
		
		/*
		 * String requests="<?xml version='1.0'?>" +
		 * "<ABE_AVDataset_1_3><Flight>CZ3101</Flight><Date>2012-03-20</Date></ABE_AVDataset_1_3>"
		 * ;
		 */
		String filter = "";
		long startTime=System.currentTimeMillis();
		// ABE_AVDataset_1_3 查询单条航班信息
		String result = service.abeSubmit(identity, requests, filter);
		System.out.println(result);

		//axis client
		/*ServiceStub serviceStub=new ServiceStub("http://183.63.31.25:38080/WebABE.asmx");
		ABESubmit aBESubmit=new ABESubmit();
		aBESubmit.setIdentity("<?xml version=\"1.0\" encoding=\"utf-8\"?><Identity_1_0><ABEConnectionString>User=AGENT00;Password=ATS123;Server=192.168.100.200;Port=350;MaxPages=30;</ABEConnectionString></Identity_1_0>");
		aBESubmit.setRequest("<?xml version=\"1.0\"?><ABE_AVDataset_1_4><From>CAN</From><Arrive>CSX</Arrive><Date>2012-07-25</Date><Carrier></Carrier><Time>0000</Time><StopType>D</StopType><Option>;CP</Option><MaxNum>1</MaxNum></ABE_AVDataset_1_4>");
		aBESubmit.setIdentity(identity);
		aBESubmit.setRequest(requests);
		aBESubmit.setFilter("");
		String result="";
		try{
		ABESubmitResponse submitResponse=serviceStub.aBESubmit(aBESubmit);
		result=submitResponse.getABESubmitResult();
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}*/
		long endTime=System.currentTimeMillis();
	    long totalSeconds = (endTime- startTime)/ 1000;
		
	    System.out.println("time:"+totalSeconds+", length:"+result.length());

		XmlConverUtil converUtil = new XmlConverUtil();

		String saleDate=DateUtil.getDateTime("yyyy-MM-dd", new Date()); 
		QueryFilter classFilter = new QueryFilter();
		classFilter.addFilter("Q_dpt_S_LK", "%"+flightCode+"%");
		classFilter.addFilter("Q_arr_S_LK", "%"+arriCode+"%");
		classFilter.addFilter("Q_startDate_D_LE", flightDate);
		classFilter.addFilter("Q_endDate_D_GE", flightDate);
		classFilter.addFilter("Q_startdateTicket_D_LE", saleDate);
		classFilter.addFilter("Q_enfdateTicket_D_GE", saleDate);
		classFilter.addFilter("Q_status_L_EQ","1");
		
		List<Policy> list = policyManager.getAll(classFilter).getList();
		converUtil.list = list;
		List newList = converUtil.xmltoList(result);

		List removeList=new ArrayList();
		for (Object object : newList) {
			Map map=(Map)object;
			ArrayList arrayList= (ArrayList) map.get("Classes");
			if(arrayList==null||arrayList.size()==0){
				removeList.add(object);
			}
		}
		newList.removeAll(removeList);
		String xml = converUtil.listtoXml(newList);

		JSONObject job = JSONML.toJSONObject(xml);
		String rs = job.toString();
		
		System.out.println(rs);
		response.getWriter().print(rs);
		
//		 response.getWriter().print("");
	}

	// 返回json机场名称
	public void getApointName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 起飞机场名称
/*		String flightName1 =new String(request.getParameter("flightName").getBytes("iso8859-1"), "UTF-8");
		String arriName1 = new String(request.getParameter("arriName").getBytes("iso8859-1"), "UTF-8");*/
		String flightCode=request.getParameter("flightCode");
		String arriCode=request.getParameter("arriCode");
		
		City flightName=cityManager.getCity(flightCode);
		
		QueryFilter filter=new QueryFilter();
		filter.addFilter("Q_ctCn_S_EQ", flightName.getCtCn());
		List<City> flightCtiys =cityManager.getAllList(filter);
		
		City arriName=cityManager.getCity(arriCode);
		QueryFilter filter2=new QueryFilter();
		filter.addFilter("Q_ctCn_S_EQ", arriName.getCtCn());
		List<City> arriCtiys =cityManager.getAllList(filter2);
		
		List<City> cities=new ArrayList<City>();
		
		cities.addAll(flightCtiys);
		cities.addAll(arriCtiys);
		String json = "{[";
		for (int i = 0; i < cities.size(); i++) {
			City city = cities.get(i);
			json = json + toJSON(city.getAptCode(), city.getAptCn());
			if (i != cities.size() - 1) {
				json = json + ",";
			}
		}
		json = json + "]}";
		response.getWriter().print(json.toString());

	}

	// 预定详细页面
	public ModelAndView bookin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// String xml=service.abeSubmit(identity, requests, "");
		// JSONObject job = JSONML.toJSONObject(xml);
		// String rs = job.toString();

		// System.out.println(rs);

		BOrder bOrder = new BOrder();
		// flight
		String policy_id = request.getParameter("policyId");
		String flightNo = request.getParameter("flight");
		String carrier = request.getParameter("carrier");
		String cabin = request.getParameter("cabin");
		String boardPointName = request.getParameter("boardPointName");
		String departure_day = request.getParameter("departure_day");
		String duptTime = request.getParameter("duptTime");
		String departure_city = request.getParameter("departure_city");
		String offPointName = request.getParameter("offPointName");
		String arrival_city = request.getParameter("arrival_city");
		String ariTime = request.getParameter("ariTime");
		String flyTime = request.getParameter("flyTime");
		String tmp = request.getParameter("tmp");
		String stop = request.getParameter("stop");

		// order
		String price = request.getParameter("price");
		String discount = request.getParameter("discount");
		String construction_fee = request.getParameter("airportTax");
		String fuel_tax = request.getParameter("fuelSurTax");
		String type = request.getParameter("type");
		String gx = request.getParameter("gx");
		String flightType = request.getParameter("flightType");

		Set<Flight> flights = new HashSet<Flight>();
		Flight flight = new Flight();
		flight.setCode(flightNo);
		flight.setCabin(cabin);
		flight.setFlightName(carrier);
		flight.setDep(departure_city);
		flight.setBoardPointName(boardPointName);
		flight.setArr(arrival_city);
		flight.setOffPointName(offPointName);
		flight.setDepTime(departure_day);
		flight.setDepTime(duptTime);
		flight.setArrDay(departure_day);
		flight.setArrTime(ariTime);
		flight.setMileage(Long.valueOf(tmp));
		flight.setFlightTime(flyTime);
		flight.setRealCode("");
		flight.setStop(Integer.valueOf(stop));
		flight.setOrder(bOrder);
		flights.add(flight);
		bOrder.setFlights(flights);

		// bOrder.setOrderType(Long.valueOf(flightType));
		bOrder.setChildFaceValue(0l);
		bOrder.setCabinnote("");
		bOrder.setSource("self");
		bOrder.setInsuranceUnitPrice(20l);
		bOrder.setBacknote("");
		bOrder.setInsuranceCuttingPrice(10l);
		bOrder.setConstructionFee(Double.valueOf(construction_fee));
		bOrder.setFuelTax(Double.valueOf(fuel_tax));

		
		List<InsuranceCompany> insurances= insuranceCompanyManager.getAll();
		
		//保险让利近
		String benefitCost=ConfigUtil.getInstance().getXmlValByStr("insurance.benefitCost", "15");
		//保险单价
		String insurancePrice=ConfigUtil.getInstance().getXmlValByStr("insurance.price", "20");
		//快递
		String xcdPrice=ConfigUtil.getInstance().getXmlValByStr("xcdPrice", "20");
		//平邮
		String surface=ConfigUtil.getInstance().getXmlValByStr("surface.mail", "5");
		
		
		ModelMap map=new ModelMap();
		Policy policy=null;
		if(StringUtils.isNotBlank(policy_id)){
			policy=policyManager.get(Long.valueOf(Long.valueOf(policy_id)));
		}
		
		boardPointName=java.net.URLDecoder.decode(boardPointName,"utf-8"); 
		offPointName = java.net.URLDecoder.decode(offPointName,"utf-8");
		
		map.addAttribute("boardPointName", boardPointName);
		map.addAttribute("offPointName", offPointName);
		map.addAttribute("policy", policy);
		map.addAttribute("benefitCost", benefitCost);
		map.addAttribute("insurancePrice", insurancePrice);
		map.addAttribute("xcdPrice", xcdPrice);
		map.addAttribute("surface", surface);
		map.addAttribute("insurances", insurances);
		return new ModelAndView("/front/order/bookin").addAllObjects(map);
	}

	public String toJSON(String name, String value) {
		return "{'name':'" + name + "','value':'" + value + "'}";
	}

	// 判断剩余座位
	public void validateFlight(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String flightNo = request.getParameter("flightNo");
		String date = request.getParameter("flightDate");

		ClientService<ServiceSoap> clientService = new ClientService<ServiceSoap>();

		ServiceSoap service = clientService.getClient("abeService.path",
				ServiceSoap.class);

		String identity = getIdentity();
		String requests = getText("abe.validateFlight", new Object[] {
				flightNo, date });

		String result = service.abeSubmit(identity, requests, "");

		JSONObject job = JSONML.toJSONObject(result);

		String rs = job.toString();
		logger.debug(rs);
//		String	rs="{\"tagName\":\"CRS.CommandSet.AV1.2\",\"childNodes\":[{\"tagName\":\"Item\",\"childNodes\":[{\"tagName\":\"ID\",\"childNodes\":[0]},{\"tagName\":\"FlightID\",\"childNodes\":[0]},{\"tagName\":\"FlightType\",\"childNodes\":[\"S\"]},{\"tagName\":\"Airline\"},{\"tagName\":\"ElementNo\"},{\"tagName\":\"Carrier\",\"childNodes\":[\"CZ\"]},{\"tagName\":\"FlightNo\",\"childNodes\":[6302]},{\"tagName\":\"ShareCarrier\",\"childNodes\":[22]},{\"tagName\":\"ShareFlight\",\"childNodes\":[37]},{\"tagName\":\"BoardPoint\",\"childNodes\":[\"CAN\"]},{\"tagName\":\"OffPoint\",\"childNodes\":[\"SHE\"]},{\"tagName\":\"DepartureDate\",\"childNodes\":[\"2012-06-29\"]},{\"tagName\":\"DepartureTime\",\"childNodes\":[\"19:50\"]},{\"tagName\":\"ArrivalDate\",\"childNodes\":[\"2012-06-29\"]},{\"tagName\":\"ArrivalTime\",\"childNodes\":[\"23:25\"]},{\"tagName\":\"Aircraft\",\"childNodes\":[320]},{\"tagName\":\"AirportTax\",\"childNodes\":[50]},{\"tagName\":\"Meal\",\"childNodes\":[\"C\"]},{\"tagName\":\"ViaPort\"},{\"tagName\":\"ETicket\"},{\"tagName\":\"ASR\"},{\"tagName\":\"LinkLevel\"},{\"tagName\":\"Class\",\"childNodes\":[\"F8 AX P4 CX DX IX JX WA Z4 YA TA KA HA MA GA SA LA QQ UA EQ VQ B7 XQ NQ RQ\"]},{\"tagName\":\"ClassEx\"},{\"tagName\":\"UsableClass\",\"childNodes\":[\"F8 P4 WA Z4 YA TA KA HA MA GA SA LA UA B7\"]},{\"tagName\":\"YClassPrice\",\"childNodes\":[-1]},{\"tagName\":\"FuelSurTax\"},{\"tagName\":\"TPM\",\"childNodes\":[0]},{\"tagName\":\"BoardPointAT\"},{\"tagName\":\"OffPointAT\"},{\"tagName\":\"FlightTime\",\"childNodes\":[\"3:35\"]}]}]}";
		response.getWriter().print(rs);
	}

	public ModelAndView apipay(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// //////////////////////////////////请求参数//////////////////////////////////////

		// 必填参数//

		// 请与贵网站订单系统中的唯一订单号匹配
		String out_trade_no = request.getParameter("orderNo");
		
		// String out_trade_no = request.getParameter("orderNo");
		// 订单名称，显示在支付宝收银台里的“商品名称”里，显示在支付宝的交易管理的“商品名称”的列表里。
		// String subject = new
		// String(request.getParameter("subject").getBytes("ISO-8859-1"),"utf-8");

		String subject = "支付宝测试";
		// 订单描述、订单详细、订单备注，显示在支付宝收银台里的“商品描述”里
		// String body = new
		// String(request.getParameter("alibody").getBytes("ISO-8859-1"),"utf-8");
		String body = "购票";

//		subject = new String(subject.getBytes("ISO-8859-1"), "utf-8");
//		body = new String(body.getBytes("ISO-8859-1"), "utf-8");

		// 订单总金额，显示在支付宝收银台里的“应付总额”里
		String total_fee = request.getParameter("noPay");
		if (StringUtils.isNotBlank(total_fee)) {
			total_fee = "0.01";
		}
		total_fee = "0.01";
		// 扩展功能参数——默认支付方式//

		// 默认支付方式，取值见“即时到帐接口”技术文档中的请求参数列表
		String paymethod = "";

		// 默认网银代号，代号列表见“即时到帐接口”技术文档“附录”→“银行列表”
		String defaultbank = request.getParameter("defaultbank");
		if (StringUtils.isNotBlank(defaultbank)) {
			if ("DEBIT".indexOf(defaultbank) != -1) {
				paymethod = "CREDITCARD";
			} else {
				paymethod = "bankPay";
			}
		}
		
		BOrder bOrder=bOrderManager.findOrderByNo(out_trade_no);
		bOrder.setPayStatus(1l);
//		out_trade_no=UtilDate.getOrderNum();
		String sHtmlText = bOrderManager.getCreateDirectPay(out_trade_no,
				subject, body, total_fee, paymethod, defaultbank);
		return new ModelAndView("/front/order/alipayto").addObject("sHtmlText",
				sHtmlText);
	}

	public ModelAndView doAffirmance(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String orderId = request.getParameter("orderId");
		String tradeNo = request.getParameter("tradeNo");
		BOrder order =null;
		if(StringUtils.isNotBlank(orderId)){
			order=bOrderManager.get(Long.valueOf(orderId));
		}else if(StringUtils.isNotBlank(tradeNo)){
			order=bOrderManager.findOrderByNo(tradeNo);
		}

		List<PassengerDto> dtos= bOrderManager.passenger2dto(order.getPassengers());
		
		ModelMap map=new ModelMap();
		map.addAttribute("order", order);
		map.addAttribute("passengerDtos", dtos);
		
		return new ModelAndView("/front/order/affirmance").addAllObjects(map);
	}

	private String getIdentity() {
		String user = ConfigUtil.getInstance().getProperty("abe.userId");
		String password = ConfigUtil.getInstance().getProperty("abe.password");
		String server = ConfigUtil.getInstance().getProperty("abe.server");
		String port = ConfigUtil.getInstance().getProperty("abe.port");
		String maxPage = ConfigUtil.getInstance().getProperty("abe.maxPage");

		String identity = getText("abe.identity", new Object[] { user,
				password, server, port, maxPage });

		return identity;
	}

	
	public void checkName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
			String name = request.getParameter("name");
		name= URLDecoder.decode(name,"GBK2312");
			String [] names=name.split("%");
			for (String string : names) {
				if(string.length()>2){
					break;
				}
			}
	}
	
}
